﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using CMN.BLL;
using CMN.Entity;
using CMN.Cache;
using CMN.Common;
using System.Web;
namespace CMN.Framework
{
    /// <summary>
    /// 用户数据存储类
    /// </summary>
    public class UserData
    {

        #region "用户资料"
        /// <summary>
        /// 根据用户ID获取用户资料(从缓存中获取)
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public static Sys_UserEntity GetSysUserEntity(int UserID)
        {
            string CacheKey = string.Format("{0}-UserInfo-{1}", Utils.GetWebCacheName, UserID);
            if (CMNCache.Instance()[CacheKey] != null)
            {
                return (Sys_UserEntity)CMNCache.Instance()[CacheKey];
            }
            else
            {
                BLLHelper bll = new BLLHelper();
                Sys_UserEntity sUT = bll.Sys_UserDisp(UserID);
                if (sUT != null)
                    CMNCache.Instance().Insert(CacheKey, sUT);
                return sUT;
            }
        }
        

        /// <summary>
        /// 根据用户登陆名,获取用户资料
        /// </summary>
        /// <param name="uLoginName">用户名</param>
        /// <returns>用户实体类</returns>
        public static Sys_UserEntity GetSysUserEntity(string uLoginName)
        {
            QueryParam qp = new QueryParam();
            qp.Where = string.Format(" U_LoginName='{0}' ",uLoginName);
            int rInt = 0;
            BLLHelper bll = new BLLHelper();
            List<Sys_UserEntity> lst=bll.Sys_UserList(qp,out rInt);
            if(lst.Count>0)
            {
                return lst[0];
            }
            else 
            {
                return null;
            }
        }

        /// <summary>
        /// 根据用户ID移除用户资料Cache
        /// </summary>
        /// <param name="UserID"></param>
        public static void MoveUserCache(int UserID)
        {
            CMNCache.Instance().Remove(string.Format("{0}-UserInfo-{1}",Utils.GetWebCacheName, UserID));
        }

        #endregion

        #region "用户权限"
        //private static Cache UserPermissionCache = HttpRuntime.Cache;
        /// <summary>
        /// 根据用户ID,应用ID,PageCode判断用户是否拥有当前权限
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="PPageCode">PageCode</param>
        /// <returns></returns>
        public static bool CheckPageCode(int UserID, string PPageCode)
        {
            Sys_UserEntity userEntity = GetSysUserEntity(UserID);
            if(userEntity==null){
                return false;
            }
            if ( userEntity.U_Type == 0) //判断用户是否为超级用户
                return true;
            bool bBool = false;
            Hashtable UserPermission = GetUserPermission(UserID);
            if (UserPermission.Count > 0)
            {
                string Key = string.Format("{0}", PPageCode);
                if (UserPermission.ContainsKey(Key))
                {
                    bBool = true;
                }
            }
            return bBool;
        }

        /// <summary>
        /// 根据用户ID,应用ID,PageCode,要检测权限数值
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="PApplicationID">应用ID</param>
        /// <param name="PPageCode">PageCode</param>
        /// <param name="CheckPermissionValue">权限值</param>
        /// <returns></returns>
        public static bool CheckPageCode(int UserID,  string PPageCode, int CheckPermissionValue)
        {
            if (GetSysUserEntity(UserID).U_Type == 0) //判断用户是否为超级用户
                return true;
            bool bBool = false;
            Hashtable UserPermission = GetUserPermission(UserID);
            if (UserPermission.Count > 0)
            {
                string Key = string.Format("{0}", PPageCode);
                if (UserPermission.ContainsKey(Key))
                {
                    if ((((Sys_RolePermissionEntity)UserPermission[Key]).P_Value & CheckPermissionValue) == CheckPermissionValue)
                    {
                        bBool = true;
                    }
                }
            }
            return bBool;
        }
        /// <summary>
        /// 检测当前用户是否为管理员/超级用户
        /// </summary>
        /// <returns>是/否</returns>
        public static bool CheckUserIsManager()
        {
            if ( UserData.GetUserData.U_Type != 0)
                return false;
            else
                return true;
        }

        /// <summary>
        /// 获取用户某个模块的权限值
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pageCode"></param>
        /// <returns></returns>
        public static int GetPermissionValue(int userId, string pageCode)
        {
            int permissionValue = 0;
            Hashtable UserPermission = GetUserPermission(userId);
            if (UserPermission.Count > 0)
            {
                string Key = string.Format("{0}", pageCode);
                if (UserPermission.ContainsKey(Key))
                {
                    permissionValue = ((Sys_RolePermissionEntity)UserPermission[Key]).P_Value;
                    
                }
            }
            return permissionValue;
        }

        /// <summary>
        /// 获取用户权限Hashtable  缓存中
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        private static Hashtable GetUserPermission(int UserID)
        {
            string Key = string.Format("{1}-Permission-{0}", UserID, Utils.GetWebCacheName);
            if (CMNCache.Instance()[Key] != null)
            {
                return (Hashtable)CMNCache.Instance()[Key];
            }
            else
            {
                Hashtable Temp = GetSys_RolePermissionEntity(UserID);
                CMNCache.Instance().Insert(Key, Temp);
                return Temp;
            }
        }

        /// <summary>
        /// 移除用户权限Cache
        /// </summary>
        /// <param name="UserID">用户ID</param>
        public static void MoveUserPermissionCache(int UserID)
        {
            CMNCache.Instance().Remove(string.Format("{1}-Permission-{0}", UserID, Utils.GetWebCacheName));
        }

        /// <summary>
        /// 移除某个角色的用户权限Cache
        /// </summary>
        /// <param name="RoleID"></param>
        public static void MoveRoleUserPermissionCache(int RoleID)
        {
            QueryParam qp = new QueryParam();
            qp.Where = string.Format(" R_RoleID={0}", RoleID);
            int RecordCount = 0;
            BLLHelper bll = new BLLHelper();
            List<Sys_UserRolesEntity> lst = bll.Sys_UserRolesList(qp, out RecordCount);
            foreach (Sys_UserRolesEntity var in lst)
            {
                MoveUserPermissionCache(var.R_UserID);
            }
        }

        
        /// <summary>
        /// 返回当前登录用户创建角色列表
        /// </summary>
        /// <returns></returns>
        public static List<Sys_RolesEntity> GetUserRols()
        {
            QueryParam qp = new QueryParam();
            if (UserData.GetUserData.U_Type != 0)
            {
                qp.Where = string.Format(" R_UserID ={0}", UserData.GetUserData.UserID);
            }
            qp.TableName = "Sys_Roles";

            qp.ReturnFields = "*";

            if (qp.Orderfld == null)
            {
                qp.Orderfld = " RoleID desc";
            }
            int RecordCount = 0;
            BLLHelper bll = new BLLHelper();
            return bll.Sys_RolesList(qp, out RecordCount);
        }
        /// <summary>
        /// 根据用户ID,获取用户模块权限列表
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        private static Hashtable GetSys_RolePermissionEntity(int UserID)
        {
            Hashtable PageCodeList = new Hashtable();
            List<Sys_RolePermissionEntity > List = new List<Sys_RolePermissionEntity>();
            QueryParam qp = new QueryParam();
            qp.Where = string.Format(" R_UserID={0} ", UserID);
            int RecordCount = 0;
            BLLHelper bll = new BLLHelper();
            List<Sys_UserRolesEntity> lst = bll.Sys_UserRolesList(qp, out RecordCount);
            foreach (Sys_UserRolesEntity var in lst)
            {
                GetRolesPermission(var.R_RoleID, List);
            }

            for (int i = 0; i < List.Count; i++)
            {
                string Key = string.Format("{0}", List[i].P_PageCode);
                if (PageCodeList.ContainsKey(Key))
                {
                    Sys_RolePermissionEntity Rpt = (Sys_RolePermissionEntity)PageCodeList[Key];
                    if (Rpt.P_Value != List[i].P_Value)
                    {
                        //PageCodeList[Key] = List[i];
                        Rpt.P_Value = Rpt.P_Value | List[i].P_Value;
                    }
                }
                else
                {
                    PageCodeList.Add(Key, List[i]);
                }
            }

            return PageCodeList;
        }

        /// <summary>
        /// 根据用户角色ID,获取权限列表
        /// </summary>
        /// <param name="RoleID">角色ID</param>
        /// <param name="List">权限列表</param>
        private static void GetRolesPermission(int RoleID, List<Sys_RolePermissionEntity> List)
        {
            QueryParam qp = new QueryParam();
            qp.Where = string.Format(" P_RoleID={0} and P_Value!=0", RoleID);
            int RecordCount = 0;
            BLLHelper bll = new BLLHelper();
            List<Sys_RolePermissionEntity> lst =bll.Sys_RolePermissionList(qp, out RecordCount);
            foreach (Sys_RolePermissionEntity var in lst)
            {
                List.Add(var);
            }
        }

        /// <summary>
        /// 检测当前用户是否可以管理当前角色ID
        /// </summary>
        /// <param name="rolesid">角色id</param>
        public static bool CheckUserIsManagerRole(int rolesid)
        {
            if (UserData.GetUserData.U_Type == 0)
                return true;
            QueryParam qp = new QueryParam();
            qp.PageIndex = 1;
            qp.PageSize = 1;
            qp.Where = string.Format(" RoleID ={0} and R_UserID={1}", rolesid, UserData.GetUserData.UserID);
            int RecordCount = 0;
            BLLHelper bll = new BLLHelper();
        bll.Sys_RolesList(qp, out RecordCount);
            if (RecordCount > 0)
                return true;
            else
                return false;
        }


        #region "根据ModuleID获取当前用户拥有权限的子菜单项"
        /// <summary>
        /// 根据ModuleID获取当前用户拥有权限的子菜单项
        /// </summary>
        /// <param name="ModuleID">ModuleID</param>
        /// <returns></returns>
        public static List<Sys_ModuleEntity> GetPermissionModuleSub(int ModuleID)
        {
            QueryParam qp = new QueryParam();
            qp.Orderfld = " M_OrderLevel ";
         
            qp.Where = string.Format("Where M_Close=0 and M_ParentID ={0}", ModuleID);
            int RecordCount = 0;
            BLLHelper bll = new BLLHelper();
            List<Sys_ModuleEntity> lst =bll.Sys_ModuleList(qp, out RecordCount);
            Remove_MenuNoPermission(lst);
            return lst;
        }
        #endregion

        #region "移除用户无权限菜单项"
        /// <summary>
        /// 移除用户无权限菜单项
        /// </summary>
        /// <param name="lst"></param>
        public static void Remove_MenuNoPermission(List<Sys_ModuleEntity> lst)
        {
            int iCount = lst.Count;
            for (int i = 0; i <= iCount; i++)
            {
                int iIndex = 0;
                foreach (Sys_ModuleEntity var in lst)
                {
                    if (!UserData.CheckPageCode(Utils.GetUserID, var.M_PageCode))
                    {
                        lst.RemoveAt(iIndex);
                        break;
                    }
                    iIndex++;
                }
            }
        }
        #endregion

        #endregion

        #region "获取当前登陆用户信息"
        /// <summary>
        /// 获取当前登陆用户信息
        /// </summary>
        public static Sys_UserEntity GetUserData
        {
            get
            {
                return GetSysUserEntity(Utils.GetUserID);
            }
        }
        #endregion
    }
}
